<template>
  <div id="wrap">
    <h1>案例-学生成绩管理系统</h1>
    <div>
      <div class="main">
        <div class="overview">班级的平均年龄为：{{ avgAge }}</div>
        <div class="tools-header">
          <button class="openModalBtn" @click="addStudent">Add New Student</button>
          <button class="openModalBtn" @click="delSelected">删除选中学生</button>
          <div>
            <input type="text" name="keyword" class="keyword" placeholder="Search by name" v-model="keyword" />
            <button type="button" class="searchBtn" @click="generateSearchData">Search</button>
          </div>
        </div>

        <table class="studentTable">
          <thead>
            <tr>
              <th><input type="checkbox" class="selectAll" v-model="isAllSclect" @click="changeSelectAll"
                  @change="changeSelectAll" /></th>
              <th>ID</th>
              <th>Name</th>
              <th>Gender</th>
              <th>Hobbies</th>
              <th>Email</th>
              <th>Phone</th>
              <th>Age</th>
              <th>Created At</th>
              <th>Updated At</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <!-- Student rows will be added dynamically here -->
            <tr v-for="item in serachStuArr" :key="item.id">
              <td>
                <input type="checkbox" class="selectAll" v-model="item.selected" @click="changeSelectItem"
                  @change="changeSelectItem" />
              </td>
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.gender }}</td>
              <td>{{ item.hobbies }}</td>
              <td>{{ item.email }}</td>
              <td>{{ item.phone }}</td>
              <td>{{ item.age }}</td>
              <td>{{ item.create_at }}</td>
              <td>{{ item.update_at }}</td>
              <td>
                <a href="javascript:void(0)" @click="delStuInfo(item)">删除</a>
                <a href="javascript:void(0)" @click="editStuInfo(item)">修改</a>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- Modal for adding/editing students -->
        <div v-show="isShowModel" class="studentModal modal" @click="closeModel">
          <div class="modal-content" @click.stop>
            <h3 class="modalTitle">{{ Infostu.title }}</h3>
            <form class="studentForm" @submit.prevent='saveStudent'>
              <input type="hidden" class="studentIdToEdit" />

              <label for="studentName">Name</label>
              <input type="text" name="name" class="studentName" v-model="stuFormDate.name" required />

              <label for="studentGender">Gender</label>
              <select name="gender" class="studentGender" v-model='stuFormDate.gender' required>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
              </select>

              <label for="studentHobbies">Hobbies</label>
              <input type="text" name="hobbies" class="studentHobbies" v-model="stuFormDate.hobbies" required />

              <label for="studentEmail">Email</label>
              <input type="email" name="email" class="studentEmail" v-model="stuFormDate.email" required />

              <label for="studentPhone">Phone</label>
              <input type="text" name="phone" class="studentPhone" v-model="stuFormDate.phone" required />

              <label for="studentAge">Age</label>
              <input type="number" name="age" class="studentAge" v-model="stuFormDate.age" required />

              <button type="submit" class="saveStudentBtn">Save Student</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: '案例学生管理系统',
}
</script>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { getFormattedCurrentDateTime } from '@/utils/Utils'
//防抖库内的生成唯一id
import { every, uniqueId } from 'lodash';
//控制弹窗的显示与消失
const isShowModel = ref(false);
//点击显示弹窗
const addStudent = () => {
  stuFormDate.value = {
    id: 1,
    name: '王小明',
    gender: 'Female',
    hobbies: '画符',
    email: 'wangxiaoming@card.com',
    phone: 123456789,
    age: 17,
    create_at: getFormattedCurrentDateTime(),
    update_at: getFormattedCurrentDateTime()
  }
  Infostu.value.type = 'add'
  Infostu.value.title = '添加学生信息'
  isShowModel.value = true
};
//点击消失弹窗
const closeModel = () => {
  isShowModel.value = false
};
//定义学生数据接口
interface ISstudent {
  id: number | string,
  name: string,
  gender: string,
  hobbies: string,
  email: string,
  phone: number | string,
  age: number | string,
  create_at?: string,
  update_at?: string,
  selected?: boolean
}
//绑定新增学生信息的输入框数据
const stuFormDate = ref<ISstudent>(
  {
    id: 1,
    name: '王小明',
    gender: 'Female',
    hobbies: '画符',
    email: 'wangxiaoming@card.com',
    phone: 123456789,
    age: 17,
  }
)

//添加studentArr数组存放默认数据
const studentArr = ref([
  {
    id: 1,
    name: 'Alice',
    gender: 'Female',
    hobbies: 'Reading',
    email: 'alice@example.com',
    phone: '12345678901',
    age: 20,
    create_at: getFormattedCurrentDateTime(),
    update_at: getFormattedCurrentDateTime()
  },
  {
    id: 2,
    name: 'Bob',
    gender: 'Male',
    hobbies: 'Sports',
    email: 'bob@example.com',
    phone: '10987654321',
    age: 22,
    create_at: getFormattedCurrentDateTime(),
    update_at: getFormattedCurrentDateTime()
  }
]);

//增加学生信息功能
const saveStudent = () => {
  //如果type属性为add，则表示现在进行的是增加操作
  if (Infostu.value.type === 'add') {
    //生成唯一id
    stuFormDate.value.id = uniqueId('newStu_')
    //转化成字符串再添加到studentArr数组内
    studentArr.value.push({
      ...JSON.parse(JSON.stringify(stuFormDate.value)),
      create_at: getFormattedCurrentDateTime(),
      update_at: getFormattedCurrentDateTime()
    });
  } else {
    //如果type不为add，则表示进行的是修改操作
    stuFormDate.value.update_at = getFormattedCurrentDateTime();
    //使用findindex查找下标
    const index = studentArr.value.findIndex((i) => i.id === stuFormDate.value.id)
    studentArr.value[index] = JSON.parse(JSON.stringify(stuFormDate.value))
  }
  changeSelectItem();
  inner();
  closeModel();
}

//计算平均年龄
const avgAge = computed(() => {
  return Math.round(
    studentArr.value.reduce(
      (previousValue, currentValue) => previousValue + Number(currentValue.age), 0
    ) / studentArr.value.length
  )
})

//实现动态修改弹窗头部标题功能
const Infostu = ref({
  type: 'add',
  title: '添加学生信息'
})


//修改学生信息
const editStuInfo = (stu: ISstudent) => {
  Infostu.value.type = 'edit'
  Infostu.value.title = '修改学生信息'
  stuFormDate.value = JSON.parse(JSON.stringify(stu))
  isShowModel.value = true
}


//删除学生信息
const delStuInfo = (item: ISstudent) => {
  const index = studentArr.value.findIndex((i) => i.id === stuFormDate.value.id);
  studentArr.value.splice(index, 1);
  changeSelectItem();
  inner();
}

//实现检索学生功能
const serachStuArr = ref<Array<ISstudent>>([]); //用来存放搜索后的数据的空数组

const keyword = ref('');
const generateSearchData = () => {
  serachStuArr.value = studentArr.value.filter((i => i.name.includes(keyword.value)))
};
//初始化
function inner() {
  //调用该函数时，当 keyword.value 为空字符串时，includes 方法对于任何非空字符串都会返回 true，因为空字符串是任何字符串的子串。因此，filter 方法会返回 studentArr.value 中的所有元素，因为每个元素的 name 属性都包含空字符串。从而实现了数组的初始化。
  generateSearchData();
}
inner();

//实现全选功能
const isAllSclect = ref(false);
const changeSelectAll = (event: Event) => {
  const checked = (event.target as HTMLInputElement).checked
  if (checked) {
    serachStuArr.value.forEach((item: ISstudent) => {
      item.selected = true
    })
  } else {
    serachStuArr.value.forEach((item: ISstudent) => {
      item.selected = false
    })
  }
}

//修改选中
const changeSelectItem = () => {
  if (serachStuArr.value.length > 0) {
    isAllSclect.value = serachStuArr.value.every((i) => i.selected)
  } else {
    isAllSclect.value = false
  }
}

const delSelected = () => {
  serachStuArr.value.forEach((i) => {
    if (i.selected) {
      delStuInfo(i)
      inner();
    }
  })
}
</script>

<style lang="scss">
@use './style/StuDemo36.scss';

.main {
  color: black;
}

input {
  color: black;
}
</style>
